//
//  RegisterViewController.m
//  QA
//
//  Created by 李小龙 on 2017/5/2.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "RegisterViewController.h"
#import "RuleViewController.h"
//#import "PerfectViewController.h"

@interface RegisterViewController ()<UITextFieldDelegate>

//@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
//@property (weak, nonatomic) IBOutlet UIView *bottomBackView;
@property (weak, nonatomic) IBOutlet UIView *phoneNumBackView;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumTF;
@property (weak, nonatomic) IBOutlet UIView *verificationBackView;
@property (weak, nonatomic) IBOutlet UITextField *verificationTF;
@property (weak, nonatomic) IBOutlet UIView *passwordBackView;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
@property (weak, nonatomic) IBOutlet UIView *passwordAgainBackView;
@property (weak, nonatomic) IBOutlet UITextField *passwordAgainTF;
@property (weak, nonatomic) IBOutlet UIView *invitationBackView;
@property (weak, nonatomic) IBOutlet UITextField *invitationTF;
@property (weak, nonatomic) IBOutlet UIView *memberInvitationBackView;
@property (weak, nonatomic) IBOutlet UITextField *memberInvitationTF;

@property (weak, nonatomic) IBOutlet UIButton *verificationButton;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UIButton *invitationButton;
@property (weak, nonatomic) IBOutlet UIButton *invitationSelectButton;

//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *invitationTopLayout;
//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomTopLayout;
//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewHLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *loginTopLayout;

@property (nonatomic, strong) NSTimer *myTimer;
@property (nonatomic, assign) NSInteger num;    // 倒计时60秒

@end

@implementation RegisterViewController
- (IBAction)passwordButtonAction:(id)sender {
    UIButton *button = (UIButton *)sender;
    [button setSelected:!button.selected];
    [self.passwordTF setSecureTextEntry:!button.selected];
}
- (IBAction)againPasswordButtonAction:(id)sender {
    UIButton *button = (UIButton *)sender;
    [button setSelected:!button.selected];
    [self.passwordAgainTF setSecureTextEntry:!button.selected];
}

#pragma mark 返回
- (IBAction)backButtonAction:(id)sender {
    if (self.type == typeRegisterPresent) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self disMissSelf];
    }
}
#pragma mark 查看邀请码规则
- (IBAction)invitationButtonAction:(id)sender {
    RuleViewController *ruleVC = [[RuleViewController alloc] init];
    [self.navigationController pushViewController:ruleVC animated:YES];
}
- (IBAction)invitationSelectButtonAction:(id)sender {
    [self.invitationSelectButton setSelected:!self.invitationSelectButton.selected];
}
#pragma mark 注册
- (IBAction)registerButtonAction:(id)sender {
    
    if (self.type == typeRegister && !self.invitationSelectButton.selected) {
        [self showAlertMessage:@"注册前请同意用户服务协议"];
        return;
    }
    if (![LXLIsPhoneNumber valiMobile:_phoneNumTF.text]) {
        [self showAlertMessage:@"请输入正确的手机号"];
        return;
    }
    if (!TextIsNotNil(_verificationTF.text)) {
        [self showAlertMessage:@"请输入验证码"];
        return;
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (!TextIsNotNil(_thirdStr)) {
        if (!TextIsNotNil(_passwordTF.text) || _passwordTF.text.length < 6 || _passwordTF.text.length > 16) {
            [self showAlertMessage:@"请输入密码，密码为6~16位的英文加数字"];
            return;
        }
        if (![_passwordTF.text isEqualToString:_passwordAgainTF.text]) {
            [self showAlertMessage:@"两次输入的密码不一致"];
            return;
        }
        [dic setObject:_passwordTF.text           forKey:@"mpass"];
        [dic setObject:_passwordAgainTF.text      forKey:@"qrpass"];
    }
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    
    [dic setObject:_phoneNumTF.text           forKey:@"mtel"];
    [dic setObject:_verificationTF.text       forKey:@"verificationcode"];
    if (TextIsNotNil(_invitationTF.text)) {
        //店铺邀请码
        [dic setObject:_invitationTF.text forKey:@"minvitationcode"];
    }
    if (TextIsNotNil(_memberInvitationTF.text)) {
        //用户邀请码
        [dic setObject:_memberInvitationTF.text forKey:@"membercode"];
    }
    NSString *url;
    switch (self.type) {
        case typeRegister: case typeRegisterPresent:
            url = URL_Regist;
            break;
        case typePassword:
            url = URL_Forgotpwd;
            break;
        case typeThirdQQ:
            url = URL_Regist_QQ;
            [dic setObject:self.thirdOpenID forKey:@"mqqid"];
            break;
        case typeThirdWechat:
            url = URL_Regist_Wechat;
            [dic setObject:self.thirdOpenID forKey:@"mwechatid"];
            break;
        default:
            break;
    }
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:url parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSDictionary *dics = responseObject;
        NSString *codes = [dics objectForKey:@"code"];
        if ([codes isEqualToString:@"200"]) {
            UserModel *model = [UserModel mj_objectWithKeyValues:dics[@"data"]];
            [UserInfo shareInstance].user = model;
            [UserInfo shareInstance].isLogin = YES;
            [UserInfo shareInstance].isOpen = model.isopen;
            [[UserInfo shareInstance] updateUserModel];
            [[UserInfo shareInstance] connectRongCloud];
            
            if (weakSelf.type == typePassword) {
                [MBProgressHUD myShowHUDAddedTo:[UIApplication sharedApplication].keyWindow labelText:@"修改成功" animated:YES];
                [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
            } else {
                [JPUSHService setAlias:[UserInfo shareInstance].user.mid completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                    NSLog(@"alias %@",iAlias);
                } seq:[UserInfo shareInstance].user.mid.integerValue];
                
                [MBProgressHUD myShowHUDAddedTo:[UIApplication sharedApplication].keyWindow labelText:@"注册成功" animated:YES];
//                PerfectViewController *view = [[PerfectViewController alloc] init];
//                [weakSelf.navigationController pushViewController:view animated:YES];
                [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
            }
            
        } else {
            [MBProgressHUD showError:weakSelf.view title:[dics safeObjectForKey:@"message"] code:codes animated:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}
#pragma mark 获取验证码
- (IBAction)verificationButtonAction:(id)sender {
    if ([LXLIsPhoneNumber valiMobile:_phoneNumTF.text]) {
        _verificationButton.userInteractionEnabled = NO;
        
        self.myTimer =  [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        //[_verificationButton setBackgroundColor:[UIColor borderColor]];
        
        __weak typeof(self) weakSelf = self;
        [MBProgressHUD showHUDProgress:self.view animated:YES];
//        [self startLoadingGifView];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:_phoneNumTF.text forKey:@"mtel"];
        NSString *md5_mobile = [NSString stringWithFormat:@"%@%@", _phoneNumTF.text, BASE_SMS_Key];
        [dic setValue:[[md5_mobile md5] lowercaseString] forKey:@"sign"];
        [dic setValue:@"2" forKey:@"vctype"];
        
        //获取验证码接口
        [MYAFNetworking POST:URL_SMS parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSDictionary *dics = responseObject;
            NSString *codes = [dics objectForKey:@"code"];
            if ([codes isEqualToString:@"200"]) {
                
            } else {
                [MBProgressHUD showError:weakSelf.view title:[dics safeObjectForKey:@"message"] code:codes animated:YES];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
        
    } else {
        [self showAlertMessage:@"请输入正确的手机号"];
    }
}
#pragma mark - UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self updateBackView];
    [self updateView];
    
    self.num = 60;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}
- (void)updateBackView {
//    UIColor *lineColor = [UIColor borderColor];
//    [self.phoneNumBackView setHalfCircleWithColor:lineColor];
//    [self.verificationBackView setHalfCircleWithColor:lineColor];
//    [self.passwordBackView setHalfCircleWithColor:lineColor];
//    [self.passwordAgainBackView setHalfCircleWithColor:lineColor];
//    [self.invitationBackView setHalfCircleWithColor:lineColor];
//    
//    [self.registerButton setHalfCircleWithColor:[UIColor whiteColor]];
    //MARK:设置背景阴影图片
//    [self.registerButton setBackgroundImage:[UIImage new] forState:UIControlStateNormal];
}
- (void)updateView {
    [self.verificationButton setCircleWithColor:[UIColor ThemeColor] borderWidth:1 cornerRadius:2];
    
    // 58 scrollView距离屏幕顶的距离
    // 三方登录
    if (self.type == typeThirdQQ | self.type == typeThirdWechat) {
        //[self.titleLabel setText:@"完善资料"];
        [self.registerButton setTitle:@"下一步" forState:UIControlStateNormal];
        
        self.passwordBackView.hidden = YES;
        self.passwordAgainBackView.hidden = YES;
        //CGFloat kong = CGRectGetMinY(self.invitationBackView.frame) - CGRectGetMaxY(self.verificationBackView.frame) - self.invitationTopLayout.constant;
        //self.invitationTopLayout.constant -= kong;
        //self.invitationTopLayout.priority = 1000;
        [self.scrollView layoutIfNeeded];
        //self.bottomViewHLayout.constant = ScreenHeight - 58 - CGRectGetMaxY(self.invitationButton.frame) - 23;
        
        //self.bottomViewHLayout.priority = 999;
        [self.scrollView layoutIfNeeded];
    }
    // 忘记密码
    if (self.type == typePassword) {
        //[self.titleLabel setText:@"忘记密码"];
        [self.registerButton setTitle:@"找回密码" forState:UIControlStateNormal];
        
        self.invitationBackView.hidden = YES;
        self.memberInvitationBackView.hidden = YES;
        self.invitationButton.hidden = YES;
        self.invitationSelectButton.hidden = YES;
        
        self.loginTopLayout.constant = 40;
        //self.bottomTopLayout.constant -= 136;
        //self.bottomTopLayout.priority = 1000;
        //self.bottomViewHLayout.constant = ScreenHeight - 58  - CGRectGetMaxY(self.passwordAgainBackView.frame)- 35;
//        self.bottomViewHLayout.constant += 136;
        //self.bottomViewHLayout.priority = 1000;
        [self.scrollView layoutIfNeeded];
    }
    // 注册
    if (self.type == typeRegister || self.type == typeRegisterPresent) {
        /*
        CGFloat bottomH = ScreenHeight - 58 - CGRectGetMaxY(self.invitationButton.frame) - 23;
        if (bottomH < 153) {
            bottomH = 153;
        }
        self.bottomViewHLayout.constant = bottomH;
        self.bottomViewHLayout.priority = 1000;
        [self.scrollView layoutIfNeeded];
         */
    }
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    [self.scrollView addGestureRecognizer:tap];
}

#pragma mark - 键盘消失
- (void)tap:(UITapGestureRecognizer *)tapGes{
    [self.view endEditing:YES];
}

#pragma mark - textFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@""]) {
        return YES;
    }
    
    if ([string isEqualToString:@" "]) {
        return NO;
    }
    if (textField.tag == 1000) {// 手机号
        if (textField.text.length >= 11) {
            return NO;
        } else {
            return YES;
        }
    } else if(textField.tag == 1001) {// 验证码
        if (textField.text.length >= 4) {
            return NO;
        }else{
            return YES;
        }
    } else if (textField.tag == 1002 || textField.tag == 1003) {// 两次密码输入
        
        if (textField.text.length >= 16 || [string isNumAndChar] == NO) {
            return NO;
        } else {
            return YES;
        }
    } else if (textField.tag == 1004) {// 邀请码
        return YES;
    } else
        return YES;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [self.view endEditing:YES];
}

- (void)timerAction{
    [_verificationButton setTitle:[NSString stringWithFormat:@"%lds",(long)self.num --] forState:UIControlStateNormal];
    
    if (_num == 0) {
        [self stopTimer];
    }
}
- (void)stopTimer {
    [_verificationButton setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
    _verificationButton.userInteractionEnabled = YES;
    //[_verificationButton setBackgroundColor:[UIColor ThemeColor]];
    _num = 60;
    [_myTimer invalidate];
}
- (void)dealloc {
    [self.myTimer invalidate];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
